#include "importar.h"

Object3D* importer(const char *ruta){
  int line = 0, asteriscos=1;
  char staux[MAXLINE];
  FILE *f;
setlocale(LC_NUMERIC,"C");
  
  int n_objects=0;
  if(!(f = fopen (ruta, "r")))
    {
      cerr << "File: " << ruta << " not found!" << endl;
      //exit(-1);//
    }
  
  while (fgets(staux, MAXLINE, f)!=NULL){

    line++;

    switch(staux[0]){

      // Comment.
    case '#':
    if (asteriscos==3){

        lista_obj[n_objects]=import_aux(f,line);
        n_objects++;
        asteriscos=0;
    }else asteriscos++;
    break;
    case 'v': break;
    case 'f': break;
    default: break;

    }// End switch.

  }// End while.
  
  fclose (f);

  return lista_obj;
}

Object3D import_aux(FILE *f,int line){
  char staux[MAXLINE];
  float a, b, c;
  GLdouble aux[3];
  float vx=0.0, vy=0.0, vz=0.0;
  Object3D obj;
  setlocale(LC_NUMERIC,"C");
  vector<Vertex3D *> vertices;
  vector<Triangle *> triangs;   
  while (fgets(staux, MAXLINE, f)!=NULL && staux[0]!='#'){

    line++;

    switch(staux[0]){

      // Comment.
    case '#':    break;
      // Vertex.
    case 'v': 

      // Read the x, y and z values.
      sscanf(&staux[2], "%f %f %f", &vx, &vy, &vz);

      aux[0] = vx; aux[1] = vy; aux[2] = vz;
      // Append a new vertex.
      vertices.push_back(new Vertex3D(aux));

      break;

      // Face.
    case 'f': 

      sscanf(&staux[2], "%f %f %f", &a, &b, &c);
                        
      Vertex3D  *t[3] = {vertices[--a], vertices[--b], vertices[--c]};
      // Store the vertex pointers.
      triangs.push_back (new Triangle(t));

      break;

    }// End switch.

  }// End while.
  

        

  for (vector<Vertex3D *>::iterator it = vertices.begin (); it != vertices.end (); it++)
    obj.add_vertex (*it);

  for (vector<Triangle *>::iterator it = triangs.begin (); it != triangs.end (); it++)
    obj.add_triangle (*it);

  return obj;
}
